package com.gcgo.zk;

import org.I0Itec.zkclient.ZkClient;

public class ServiceRegistry {
    public static final String BASE_SERVICE = "/service";
    public static final String CHILDREN = "/child";
    public static final String TIME = "/time";
    private String registryAddress;//zk地址
    private ZkClient zkClient;

    public ServiceRegistry(String registryAddress) {
        this.registryAddress = registryAddress;
    }

    public ServiceRegistry(String registryAddress, boolean init) {
        if (init) {
            this.registryAddress = registryAddress;
            this.zkClient = connectServer();
        }
        while (true) {
            if (this.zkClient != null) {
                break;
            }
        }
    }

    //注册服务端到zk
    public void register(String data) {
        if (data != null) {
            ZkClient zk = connectServer();
            boolean exists = zk.exists(BASE_SERVICE + CHILDREN);
            if (!exists) {//先创建一个service永久节点
                zk.createPersistent(BASE_SERVICE + CHILDREN, true);
                zk.createPersistent(BASE_SERVICE + TIME, true);
            }
            //创建服务子节点
            createNode(zk, data);
        }
    }

    private void createNode(ZkClient zk, String data) {
        String path = zk.createEphemeralSequential(BASE_SERVICE + CHILDREN + "/c", data);
        System.out.println("创建了 zookeeper 节点 ({" + path + "} => {" + data + "})");
        //接着建立时间节点
        String[] split = path.split("/");
        split[2] = "time";
        String timePath = String.join("/", split);
        zk.createEphemeral(timePath, 0L);
        System.out.println("创建对应的 响应时间 节点 ({" + timePath + "} => {" + 0L + "})");
    }

    private ZkClient connectServer() {
        return new ZkClient(registryAddress);
    }

    public void updateTime(long deltaTime, String nodePath) {
        System.out.println("更新响应时间");
        zkClient.writeData(nodePath, deltaTime);
    }
}
